<?php
// ini_set('display_errors',1);            //错误信息  
// ini_set('display_startup_errors',1);    //php启动错误信息  
// error_reporting(-1); 
header("Content-Type:text/html; charset=utf-8");
date_default_timezone_set('PRC');
require_once('config.php');
$conn = mysqli_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname);
function download($url,$path)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  $file = curl_exec($ch);
  curl_close($ch);
  $resource = fopen($path, 'a');
  fwrite($resource, $file);
  fclose($resource);
}
function randomkeys($length) 
{   
   //$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ'; 
      $str = null;
      $strPol = "1234567890";//大小写字母以及数字
      $max = strlen($strPol)-1;
      
      for($i=0;$i<$length;$i++){
         $str.=$strPol[rand(0,$max)];
      }
      return $str;
}
function randomsku($length)   
{   
   $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';  
    for($i=0;$i<$length;$i++)   
    {   
        $key .= $pattern{mt_rand(0,35)};    //生成php随机数   
    }   
    return $key;
}
function trimd($str){
$str=str_replace("\t"," ",$str);
$str=str_replace("'","''",$str);
$str=str_replace("\r","",$str);
$str=str_replace("$","",$str);
$str=str_replace("\n","<br/>",$str);
$str=str_replace("<br/>","\r\n",$str);
return trim($str);
}
function ensure_writable_dir($dir) {
    if(!file_exists($dir)) {
        mkdir($dir, 0766, true);
        chmod($dir, 0766);
        chmod($dir, 0777);
    }
    else if(!is_writable($dir)) {
        chmod($dir, 0766);
        chmod($dir, 0777);
        if(!is_writable($dir)) {
            echo '{State:"UnImage","content":""}';
            exit;
        }
    }
}
function rpa($str){
return substr($str,0,strlen($str)-1); 
}
$extensions = array(
        'image/bmp' => 'bmp',
        'image/gif' => 'gif',
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/x-icon' => 'ico'
    );

 
$data = json_decode($_POST["data"], true);

$lastversion="20190307115800";
$version=$data['Version'];
if($lastversion!==$version){
echo '{State:"UnVersion","content":""}';
exit;
}

$action=trimd($_GET["action"]);

$user=trimd($_GET["u"]);
$ucalist="select * from ph_admin where admin='".$user."'";
$ucaresult=mysqli_query($conn,$ucalist);
if(mysqli_num_rows($ucaresult)<1){
echo '{State:"UnUser","content":""}';
exit;
}else{
$rowuser = mysqli_fetch_array($ucaresult);
$ucalist2="select * from ph_admin where admin='".$rowuser["parent"]."'";
$ucaresult2=mysqli_query($conn,$ucalist2);
$rowuser2 = mysqli_fetch_array($ucaresult2);
if($rowuser["thetype"]=="超级管理员"||$rowuser["thetype"]=="管理员"||$rowuser2["thetype"]=="超级管理员"){
$maxhostsize=$rowuser["maxhostsize"];
$currenthostsize=$rowuser["currenthostsize"];
$uid=$rowuser["ID"];
}else{
$maxhostsize=$rowuser2["maxhostsize"];
$currenthostsize=$rowuser2["currenthostsize"];
$uid=$rowuser2["ID"];
}
}
if($action=="check"){
  echo '{State:"TitleOK","content":""}';
  exit;
}
if($action=="imageurl"){
  $Url=$data['Url'];
 //远程
 if(!empty($Url)){
    $header_array = get_headers($Url, true);
    $hz=$extensions[$header_array['Content-Type']];
    $size = $header_array['Content-Length']/1024;
  if((int)($size+$currenthostsize)>$maxhostsize){
      echo '{State:"UnSize","content":""}';
      exit;
  }
  mysqli_query($conn,"update ph_admin set currenthostsize=currenthostsize+".$size." where id='".$uid."'");
  $pathimgnew='files/'.$uid.'/'.date("Y-m-d",time()).'/';
  $pathimg=$pathimgnew.randomkeys(8).strtotime(date("Y-m-d H:i:s",time())).".".$hz;
  ensure_writable_dir($pathimgnew);
  download($Url,$pathimg); 
  mysqli_query($conn,"INSERT INTO ph_img(imgpath)VALUES('/".$pathimg."');");
  $imgid=mysqli_insert_id($conn);
  //echo '{"Imgid":"'.$imgid.'"}';
  echo '{State:"ImgOK","content":"'.$imgid.'"}';
  }else{
    echo '{State:"UnImage","content":""}';
    exit;
  }
}elseif($action=="imagebase64"){
  $ImagesBase64=$data['ImagesBase64'];
  $Extension=$data['Extension'];
  if(!empty($ImagesBase64)){
  //本地
  $imgfile= base64_decode($ImagesBase64);
  $size=strlen($imgfile)/1024;
  if((int)($size+$currenthostsize)>$maxhostsize){
      echo '{State:"UnSize","content":""}';
      exit;
  }
  $pathimgnew='files/'.$uid.'/'.date("Y-m-d",time()).'/';
  $pathimg=$pathimgnew.randomkeys(8).strtotime(date("Y-m-d H:i:s",time())).$Extension;
  ensure_writable_dir($pathimgnew);
  $r = file_put_contents($pathimg, $imgfile);
  mysqli_query($conn,"INSERT INTO ph_img(imgpath)VALUES('/".$pathimg."');");
  $imgid=mysqli_insert_id($conn);
  // echo $imgid."|||";
  // echo "/".$pathimg."|||";
  echo '{State:"ImgOK","content":"'.$imgid.'"}';
  }else{
    echo '{State:"UnImage","content":""}';
    exit;}
}elseif($action=="product"){
//$myfile = fopen("test.txt", "w") or die("Unable to open file!");
//fwrite($myfile,$_POST["data"]);
//fclose($myfile);
//exit;
$Platform=$data['Platform'];
//echo $Platform."<br/>";
$Category=trimd($data['Category']);
//echo $Category."<br/>";
$Url=trimd($data['Url']);
//echo $Url."<br/>";
$Proname=trimd($data['Proname']);
//echo $Proname."<br/>";
$Price=htmlspecialchars($data['Price']);
//echo $Price."<br/>";
$Currency=$data['Currency'];
//echo $Currency."<br/>";
$Shopname=trimd($data['Shopname']);
$Keywords=isset($data['Keywords'])?join('\r\n',$data['Keywords']):'';
//echo $Shopname."<br/>";
$Sketch=trimd($data['Sketch']);
//echo $Sketch."<br/>";
$Description=trimd($data['Description']);
if($Description=="NotFound"&&!empty($Sketch)){$Description=$Sketch;$content=$Sketch;}
if($Description!=="NotFound"&&empty($Sketch)){$Sketch=$Description;$content=$Description;}
if($Description!=="NotFound"&&!empty($Sketch)){$content=$Description;}
if($Platform=="AliExpress"){$Sketch=$Description;$content=$Description;}
//echo $Description."<br/>";
$PID=$data['PID'];
//echo $PID."<br/>";
$Images=$data['Images'];
$Attribute=$data['Attribute'];
$Products=$data['Products'];
if(empty($Url)||empty($Category)||empty($Price)||empty($Proname)){
  echo '{State:"UnField","content":""}';
  exit;
}

$calist="select * from ph_bcategory where bname='".$Category."' and platform='".$Platform."' and user_name='".$user."'";
$caresult=mysqli_query($conn,$calist);
if(mysqli_num_rows($caresult)<1){
$sqlca = "INSERT INTO ph_bcategory(bname,platform,user_name)VALUES('".$Category."','".$Platform."','".$user."')";
mysqli_query($conn,$sqlca);
}
$Arrtsname=array();
foreach ($Attribute as $key=>$Value) {
  array_push($Arrtsname,$key);
}
if(count($Arrtsname)>1){$shuxing="ColorSize";}else{$shuxing=$Arrtsname[0];}
$sql = "INSERT INTO ph_products(proname,price,saleprice,skucode,coin,code,content,ndate,bname,user_name,des,keywords,weight,kucun,btname,fromurl,shopname,platform,sketch,sid)VALUES('".$Proname."','".$Price."','".$Price."','".randomsku(19)."','".$Currency."','".randomkeys(13)."','".trimd($content)."','".date("Y-m-d",time())."','".$Category."','".$user."','".$Description."','".$Keywords."','1','50','".trimd($shuxing)."','".$Url."','".$Shopname."','".$Platform."','".$Sketch."','".$PID."')";
mysqli_query($conn,$sql);
$proid=mysqli_insert_id($conn);
if(!empty($Products[0]["Images"])){
for($p=0;$p<count($Products[0]["Images"]);$p++){

    //mysqli_query($conn,"update ph_img set proid='".$proid."' where id='".$Products[0]["Images"][$p]."'");  
    mysqli_query($conn,"INSERT INTO ph_proimg(imgid,proid)VALUES('".$Products[0]["Images"][$p]."','".$proid."');"); 
}}
for($i=0;$i<count($Products);$i++){
  $sx="";
  if(stripos($Arrtsname[0],"col")===false){
    for($r=count($Products[$i]["Value"])-1;$r>=0;$r--){
    $sx.=$Products[$i]["Value"][$r].",";
    }
  }else{
    for($r=0;$r<count($Products[$i]["Value"]);$r++){
    $sx.=$Products[$i]["Value"][$r].",";
    }
  }
  mysqli_query($conn,"INSERT INTO ph_shuxing(cname,proid,price,saleprice,kucun,skucode,sid)VALUES('".trimd(rpa($sx))."','".$proid."','".trimd($Products[$i]["Price"])."','".trimd($Products[$i]["Price"])."','50','','".trimd($Products[$i]["SID"])."');");
    $btid=mysqli_insert_id($conn);
  if(!empty($Products[$i]["Images"])){
    for($t=0;$t<count($Products[$i]["Images"]);$t++){
    //mysqli_query($conn,"update ph_img set proid='".$proid."',btid='".$btid."' where id='".$Products[$i]["Images"][$t]."'");
    mysqli_query($conn,"INSERT INTO ph_proimg(imgid,proid,btid)VALUES('".$Products[$i]["Images"][$t]."','".$proid."','".$btid."');");
    }
  }

}

for($i=0;$i<count($Images);$i++){

  //mysqli_query($conn,"update ph_img set proid='".$proid."' where id='".$Images[$i]."'");
  mysqli_query($conn,"INSERT INTO ph_proimg(imgid,proid)VALUES('".$Images[$i]."','".$proid."');");
  }
 echo '{State:"Ok","content":""}';
 }
?>